﻿using System;
using TestingConcurrencyBenchmark.Helpers;

namespace TestingConcurrencyBenchmark.Problems.ProducerConsumer
{
    class ProducerConsumerWithRaceCondition : AbstractProducerConsumer
    {
        private readonly BenchmarkSemaphore _mutex  = new BenchmarkSemaphore(1);
        
        public override void Consume()
        {
            Items.WaitOne();
            _mutex.WaitOne();
            Action action = Buffer.Peek();
            _mutex.Release();
            _mutex.WaitOne();
            Buffer.Dequeue();
            _mutex.Release();
            action.Invoke();
        }

        public override void Produce(Action action)
        {
            _mutex.WaitOne();
            Buffer.Enqueue(action);
            _mutex.Release();
            Items.Release();
        }
    }
}
